package com.inwavetech.os;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import com.inwavetech.os.entity.Os;

import java.io.FileOutputStream;
import java.util.UUID;

public class SignatureActivity extends BaseOsCheckActivity {

    private DrawingView drawingView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signature);

        // check the user login + redirect, get the os from intent and check the os ownership
        Os os = getUserOs();

        if (os == null) {
            backToMain();

            return;
        }

        //get drawing view
        DrawingView drawingView = getDrawingView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.signature, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        DrawingView drawingView = getDrawingView();

        switch (item.getItemId()) {

            case R.id.clear:

                drawingView.clearBoard();

                break;

            case R.id.capture:
                Os os = getOs();

                if (os != null) {
                    os.signature_filename = UUID.randomUUID().toString();

                    if (saveFile(os.signature_filename)) {
                        updateOs(os);
                    }
                }

                Intent i = buildFinishIntent(os.id);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);

                break;
        }

        return super.onOptionsItemSelected(item);
    }



    private DrawingView getDrawingView() {
        if (drawingView == null) {
            drawingView = (DrawingView) findViewById(R.id.drawing);
        }

        return drawingView;
    }

    private boolean saveFile(String filename) {
        try {
            FileOutputStream outputStream = openFileOutput(filename, SignatureActivity.MODE_PRIVATE);
            Bitmap bitmap = drawingView.getBitmap();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.close();
        } catch (Exception e) {
            // could not save the file
            logError(e);

            return false;
        }

        return true;
    }
}
